package cn.z2huo.usercenter.authentication.app.redis;

import com.fasterxml.jackson.databind.json.JsonMapper;
import org.redisson.codec.JsonJacksonCodec;
import org.redisson.config.Config;
import org.redisson.spring.starter.RedissonAutoConfigurationCustomizer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.PropertyMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ResourceUtils;

import java.io.IOException;

/**
 * <p>
 *
 * @author z2huo
 */
@Configuration
public class RedissonConfig {

    @Autowired
    @Qualifier("redisJsonMapper")
    private JsonMapper jsonMapper;

    @Bean
    public RedissonAutoConfigurationCustomizer redissonCustomizer() {

        return configuration -> {
            try {
                Config redissonConfig = Config.fromYAML(ResourceUtils.getFile("classpath:redisson.yaml"));
                PropertyMapper propertyMapper = PropertyMapper.get().alwaysApplyingWhenNonNull();
                propertyMapper.from(redissonConfig::getLockWatchdogTimeout).to(configuration::setLockWatchdogTimeout);

                configuration.setCodec(new JsonJacksonCodec(jsonMapper));
            } catch (IOException e) {
                throw new RuntimeException("redisson.yaml config file don't exists!", e);
            }
        };
    }

}
